package com.KKB.service.impl;

import com.KKB.bean.Menu;
import com.KKB.bean.Role;
import com.KKB.dao.MiddleDao;
import com.KKB.dao.RoleDao;
import com.KKB.dao.impl.MiddleDaoImpl;
import com.KKB.dao.impl.RoleDaoImpl;
import com.KKB.service.RoleService;

import java.util.ArrayList;
import java.util.List;

public class RoleServiceImpl implements RoleService {
    private RoleDao roleDao=new RoleDaoImpl();
    private MiddleDao middleDao=new MiddleDaoImpl();
    @Override
    public List<Role> getRoleList(int pageIndex, int pageSize) {
        return roleDao.getRoleList(pageIndex, pageSize);
    }

    @Override
    public int total() {
        return roleDao.total();
    }

    @Override
    public int insertRole(String rolename, String state, String[] ids) {
        int k1=0;
        try {

            Role role = new Role();
            role.setRoleName(rolename);
            role.setRoleState(Integer.parseInt(state));
            int k = roleDao.insert(role);

            middleDao.insertMiddle(k,ids);
            k1=1;
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        return k1;
    }

    @Override
    public List<Role> getList() {
        return roleDao.getList();
    }

    @Override
    public int update(Role role, String[] menuIds) {
        int result = 0;
        try {
            roleDao.update(role);
            middleDao.delete(role.getRoleId());
            middleDao.insertMiddle(role.getRoleId(), menuIds);
            result = 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public Role findById(int rid) {
        Role role = roleDao.findById(rid);
        List<Menu> menuList = role.getMenuList();
        List<Menu> newMenuList = new ArrayList<>();

        for (Menu menu : menuList) {
            if (menu.getUpmenuID() == 0) {
                List<Menu> secondMenuList = new ArrayList<>();
                for (Menu second : menuList) {
                    if (second.getUpmenuID() == menu.getMenuId()) {
                        secondMenuList.add(second);
                    }
                }
                menu.setSecondMenuList(secondMenuList);
                newMenuList.add(menu);
            }
        }

        role.setMenuList(newMenuList);
        return role;
    }

    @Override
    public int deleteById(int roleId) {
        int result = 0;
        try {
            // 先删中间表记录，再删除角色表
            middleDao.delete(roleId);
            roleDao.deleteById(roleId);
            result = 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
